import { s_getcommontableinfo, s_getSelectData, s_getTableInfo, s_operateInfo, s_produce_updateInfo, s_updateInfo, status2text } from "@/services/basis";
import { ActionType, EditableFormInstance, EditableProTable, ProCard, ProColumns, ProForm, ProFormDatePicker, ProFormDigit, ProFormInstance, ProFormRadio, ProFormSelect, ProFormText, ProFormTextArea, ProTable } from "@ant-design/pro-components";
import { useModel } from "@umijs/max";
import { Button, Col, message, Modal, Row, Space, Tag } from "antd";
import moment from "moment";
import { useRef, useState } from "react";

const App:React.FC=()=>{
    const formRef_main=useRef<ProFormInstance>();
    const formRef_detail=useRef<ProFormInstance>();
    const editableRef_detail=useRef<EditableFormInstance>();
    const actionRef_detail=useRef<ActionType>();
    const actionRef_main=useRef<ActionType>();

    const [open,setOpen]=useState(false);
    const [etype,setEtype]=useState(1);
    const [selectedRecord,setSelectedRecord]=useState<any[]>([]);

    const [openDetail,setOpenDetail]=useState(false);
    const [etype2,setEtype2]=useState(1);
    const [selectedRecord2,setSelectedRecord2]=useState<any[]>([]);
   
    const [moptions,setMoptions]=useState([]);

    const [openRate,setOpenRate]=useState(false);
    const formRef_rate=useRef<ProFormInstance>();
    const [etype3,setEtype3]=useState(1);
    const actionRef_ratio=useRef<ActionType>();

    const { initialState, setInitialState } = useModel('@@initialState');
    const [selectedLineKeys,setSelectedLineKeys]=useState<any[]>([]);
    const [selectedLineKeys2,setSelectedLineKeys2]=useState<any[]>([]);

    interface DataType{
       id?:number,code?:string,name?:string,begindate?:string,enddate?:string,status?:number,
    };

    const columns:ProColumns<DataType>[]=[
        {dataIndex:'id',hidden:true},
        {dataIndex:'name',title:'工资表'},
        {dataIndex:'status',title:'状态',
          render:(text:any)=>status2text(text),
        },
    ];
 
    interface DataType2{
        rid?:number,id?:number,card_id?:number,card_name?:string,
        material_id?:number,code?:string,name?:string,invstd?:string,munit_name?:string,
        type?:number,banchi:string,
        price?:number,status?:number,
        default_rate?:number,memo?:string,
    }   

    const columns2:ProColumns<DataType2>[]=[
      {dataIndex:'rid',title:'rid',hidden:true,},{dataIndex:'id',title:'id',hidden:true},
      {dataIndex:'card_id',hidden:true},{dataIndex:'classes_id',hidden:true},
      {dataIndex:'type',title:'计件类型',valueType:'select',
        valueEnum:{1:{text:'产量'},2:{text:'工序'},3:{text:'产量+工序'}}
      },
      {dataIndex:'material_id',hidden:true},
      {dataIndex:'card_name',title:'工序名称'},
      {dataIndex:'code',title:'SKU编码'},{dataIndex:'name',title:'名称'},{dataIndex:'invstd',title:'包装规格'},
      {dataIndex:'munit_name',title:'单位'},
      {dataIndex:'classes_name',title:'班次',},
      {dataIndex:'price',title:'计件单价'},
      {dataIndex:'default_rate',title:'默认系数'},{dataIndex:'memo',title:'备注'}, 
      {dataIndex:'status',title:'状态',
          render:(text:any)=>status2text(text),
      },
    ];
    
    interface DataType3{
       mid?:number,id?:number,item_name?:string,item_rate?:number,status?:number,isdefault?:number,memo?:string,
    };

    const columns3:ProColumns<DataType3>[]=[
      {dataIndex:'mid',title:'mid'},{dataIndex:'id',title:'ID'},
      {dataIndex:'item_name',title:'系数名'},{dataIndex:'item_rate',title:'系数'},
      {dataIndex:'isdefault',title:'默认',valueType:'select',valueEnum:{1:{text:'是'},0:{text:'否'}}},
      {dataIndex:'memo',title:'备注'},
      {dataIndex:'status',title:'状态',valueType:'select',valueEnum:{1:{text:'有效'},2:{text:'关闭'}}},
  
    ];
   //  新建价格表
     function addPriceSchedule(){
       setEtype(1);
       setOpen(true);
    };

    //  编辑价格表
    function editPriceSchedule(){
      if(selectedRecord[0].status==5||selectedRecord[0].status==2)
            message.warning('价格表已审核或关闭，请先取消审核或关闭！');
      else{
            setEtype(0);
            setOpen(true);
      };
   };


    function closePriceSchedule(){
      setEtype(1);
      setOpen(false);
    };

    async function savePriceSchedule(){
      // alert(JSON.stringify(formRef_main.current?.getFieldsValue()));
      var fdata=formRef_main.current?.getFieldsValue();
      fdata={...fdata,
         begindate:moment(moment(fdata.begindate).toDate()).format('YYYY-MM-DD HH:mm:ss'),
         enddate:moment(moment(fdata.enddate).toDate()).format('YYYY-MM-DD HH:mm:ss'),
      };
      // source,x_id,operater_id,etype,JSON.stringify(fdata)
      const x=await s_updateInfo({source:'produce_pricerate_main',x_id:1,
                  operater_id:initialState?.currentUser?.userid,etype,fdata});
      if(x.success){
         actionRef_main.current?.reloadAndRest?.();
         message.success('保存成功');
        }
      else
        message.error('保存失败，请联系管理员');
    };

    //  操作主表
       async function operateInfo(n:number){
        // source,x_id,operater_id,otype,id
        if(selectedRecord.length==0)
           message.warning('请选择要操作的行');
        else{
         const x=await s_operateInfo({x_id:1,source:'produce_pricerate_main',
               operater_id:initialState?.currentUser?.userid,otype:n,id:selectedRecord[0].id});
         if(x.success){
           message.success('操作成功');
           actionRef_main.current?.reloadAndRest?.();
         }else
           message.error('失败，请联系管理员。');
        }
     };
     
     function closePriceDetail(){
         setOpenDetail(false);
         // setSelectedRecord([]);
         // setSelectedRecord2([]);
         // actionRef_detail.current?.reset?.();
         // actionRef_main.current?.reset?.();
     };

     //  新建明细表
     function addPriceDetail(){
      if(selectedRecord.length==0)
         message.warning('请先选择价格表');
      else if(selectedRecord[0].status==5||selectedRecord[0].status==2)
         message.warning('价格表已审核或关闭，请先取消审核或关闭！');
      else{
        setEtype2(1);
        setOpenDetail(true);
      };
   };

   //  编辑明细表
   function editPriceDetail(){
      if(selectedRecord2.length==0)
         message.warning('请先选择要编辑的明细行');
      else if(selectedRecord[0].status==5||selectedRecord[0].status==2)
         message.warning('价格表已审核或关闭，请先取消审核或关闭！');
      else{
        setEtype2(0);
        setOpenDetail(true);
      };
  };

  async function savePriceDetail(){
   // alert(JSON.stringify(formRef_main.current?.getFieldsValue()));
   var fdata=formRef_detail.current?.getFieldsValue();
   fdata={...fdata,
      material_id:fdata.material_id2?fdata.material_id2:fdata.material_id,
      mid:selectedRecord[0].id};
   //  alert(JSON.stringify(fdata));
   // source,x_id,operater_id,etype,JSON.stringify(fdata)
   const x=await s_updateInfo({source:'produce_pricerate_detail',x_id:1,
           operater_id:initialState?.currentUser?.userid,etype:etype2,fdata});
   if(x.success){
      actionRef_detail.current?.reloadAndRest?.();
      message.success('保存成功');
     }
   else
     message.error('保存失败，请联系管理员');
 };

 //  操作明细表
 async function operateInfo2(n:number){
   // source,x_id,operater_id,otype,id
   if(selectedRecord2.length==0)
      message.warning('请选择要操作的行');
   else{
    const x=await s_operateInfo({x_id:1,source:'produce_pricerate_detail',
             operater_id:initialState?.currentUser?.userid,
                   otype:n,id:selectedRecord2[0].id});
    if(x.success){
      message.success('操作成功');
      actionRef_detail.current?.reloadAndRest?.();
    }else
      message.error('失败，请联系管理员。');
   }
};

function setRate(){
   setOpenRate(true)
} ;

//新增系数
function addRatio(){
   formRef_rate.current?.resetFields();
   setEtype3(1);
};

//关闭窗口
function exitRatio(){
   setEtype3(1);
   setOpenRate(false);
};

//保存系数
async function saveRatio(){
   var fdata=formRef_rate.current?.getFieldsValue();
   if(etype3==1)
     fdata={...fdata,
         //   id:selectedRecord2.length>0?selectedRecord2[0].id:0,
        mid:selectedRecord2.length>0?selectedRecord2[0].id:0,
      };

   //  alert(JSON.stringify(fdata));
   const x=await s_produce_updateInfo({source:'produce_pricerate_detail_ratio',
                           x_id:1,etype:etype3,operater_id:initialState?.currentUser?.userid,fdata});
   if(x.success){ 
      actionRef_ratio.current?.reloadAndRest?.();
      message.warning('保存成功');
   }
   else
     message.error('保存失败，请联系管理员');
    
}

//   ============================================================================================================
    return <>
       <Row gutter={8}>
          <Col span={6}>
             <ProCard title='计件工资设置' style={{height:'75vh'}}
               >
                <Space>
                    <Button onClick={()=>addPriceSchedule()}>新增</Button>
                    <Button onClick={()=>editPriceSchedule()}>编辑</Button>
                    <Button onClick={()=>operateInfo(5)}>审核</Button>
                    <Button onClick={()=>operateInfo(6)}>取审</Button>
                    <Button onClick={()=>operateInfo(2)}>关闭</Button>
                    <Button onClick={()=>operateInfo(1)}>恢复</Button>
                </Space>
                 <ProTable<DataType>
                   rowKey='id'
                   columns={columns}
                   search={false}
                   options={false}
                   actionRef={actionRef_main}
                   rowSelection={{
                     type:'radio',
                     selectedRowKeys:selectedLineKeys,
                     onChange(selectedRowKeys, selectedRows, info) {
                        setSelectedRecord(selectedRows);
                        setSelectedLineKeys(selectedRowKeys);
                        actionRef_detail.current?.reloadAndRest?.();
                     },
                   }}
                   onRow={(record)=>{
                    return {
                      onClick:()=>{
                          const k=record.id;
                // if(selectedKeys.includes(k) )
                //      setSelectedKeys(selectedKeys.filter(item=>item.id!=k));
                // else
                     setSelectedLineKeys([k]);
                     setSelectedRecord([record]);
                     actionRef_detail.current?.reloadAndRest?.();
                  },
                 }
                  }}
                   request={async ()=>{
                     // source,x_id,id
                     const x=await s_getTableInfo({source:'produce_pricerate_main',x_id:1});
                     // alert(JSON.stringify(x.data));
                     return{
                        data:x.data,
                        success:true,
                     }
                   }}
                 />
             </ProCard>
          </Col>
          <Col span={18}>
          <ProCard title='计件明细表' style={{height:800}}
          extra={<Space>
            <Button onClick={()=>addPriceDetail()}>新增</Button>
            <Button onClick={()=>editPriceDetail()}>编辑</Button>
            {/* <Button onClick={()=>operateInfo2(2)}>关闭</Button>
            <Button onClick={()=>operateInfo2(1)}>恢复</Button> */}
          </Space>}
       >
          <ProForm submitter={false} layout="horizontal" labelAlign="left" labelCol={{offset:0,span:5}}
              labelWrap  formRef={formRef_detail}
          >
           <EditableProTable<DataType2>
             name='editable'
             rowKey='rid'
             editableFormRef={editableRef_detail}
             actionRef={actionRef_detail}
             columns={columns2}
            //  dataSource={tdata}
             search={false}
             rowSelection={{
                type:'radio',
                selectedRowKeys:selectedLineKeys2,
                onChange(selectedRowKeys, selectedRows, info) {
                   setSelectedRecord2(selectedRows);
                   setSelectedLineKeys2(selectedRowKeys);
                },
             }}
             onRow={(record)=>{
              return {
               onClick:()=>{
                   const k=record.rid;
                // if(selectedKeys.includes(k) )
                //      setSelectedKeys(selectedKeys.filter(item=>item.id!=k));
                // else
                     setSelectedLineKeys2([k]);
                     setSelectedRecord2([record]);
              },
            }
           }}
             recordCreatorProps={false}
             editable={{
                type:'multiple'
             }}
             request={async ()=>{
               var mid=selectedRecord.length>0?selectedRecord[0].id:0;
               // x_id,cate_id,id,source,fdata
               const x=await s_getcommontableinfo({x_id:1,id:mid,source:'v_produce_pricerate_detail'});
               return{
                  data:x.data[0],
                  success:true,
               }
             }}
            />
            </ProForm>
       </ProCard>
          </Col>
       </Row>
       {/* 新增价格主表----------------------------------------------------------- */}
       <Modal open={open} closable onCancel={()=>closePriceSchedule()} onClose={()=>closePriceSchedule()}
           okButtonProps={{hidden:true}} cancelButtonProps={{hidden:true}} destroyOnClose width={800}
         >
         <ProCard title='计件价格表' 
             extra={<Space>
                  <Button onClick={()=>formRef_main.current?.submit()}>保存</Button>
                  <Button onClick={()=>closePriceSchedule()}>退出</Button>
              </Space>}>  
         <ProForm submitter={false} formRef={formRef_main}  onFinish={()=>savePriceSchedule()}
            layout="horizontal" labelAlign="left" labelCol={{offset:0,span:5}} labelWrap
            initialValues={etype==1?{status:1,begindate:moment(),enddate:moment()}
                           :{...selectedRecord[0]}}
         >
            <ProFormText name='id' label='ID' hidden width={200} />
            <ProFormText name='code' label='编码' width={200} />
            <ProFormText name='name' label='名称' width={200}
                rules={[{required:true,message:'必填项'}]}
            />
            <ProFormDatePicker name='begindate' label='生效日期' width={200} 
               rules={[{required:true,message:'必填项'}]}
            />
            <ProFormDatePicker name='enddate' label='失效日期' width={200} 
               rules={[{required:true,message:'必填项'}]}
            />
            <ProFormTextArea name='memo' label='备注' width={300} />
            <ProFormRadio.Group name='status' label='状态' width={200} 
               rules={[{required:true,message:'必填项'}]}
               options={[{value:1,label:'正常'},{value:2,label:'关闭'},{value:3,label:'删除'}]}
            />
         </ProForm>
         </ProCard>
       </Modal>
{/* 新增价格明细表----------------------------------------------------------- */}
<Modal open={openDetail} closable onCancel={()=>closePriceDetail()} onClose={()=>closePriceDetail()}
           okButtonProps={{hidden:true}} cancelButtonProps={{hidden:true}} destroyOnClose width={800}
         >
         <ProCard title='计件价格明细表' 
             extra={<Space>
                  <Button onClick={()=>formRef_detail.current?.submit()}>保存</Button>
                  <Button onClick={()=>closePriceDetail()}>退出</Button>
              </Space>}>  
         <ProForm submitter={false} formRef={formRef_detail}  onFinish={()=>savePriceDetail()}
            layout="horizontal" labelAlign="left" labelCol={{offset:0,span:5}} labelWrap
            style={{marginLeft:100}}
            initialValues={etype2==1?{status:1 }
                           :{...selectedRecord2[0]}}
         >
            <ProFormText name='id' label='ID' hidden width={300} />
            <ProFormText name='mid' hidden width={200} />

            <ProFormSelect name='type' label='计件类型' width={300}
                rules={[{required:true,message:'必填项'}]}
                options={[{value:1,label:'产量'},{value:2,label:'工序'},{value:3,label:'产量+工序'}]}
            />
            <ProFormSelect name='material_id' label='SKU码' width={300} 
                 request={async (p)=>{
                     const x=await s_getSelectData({x_id:1,
                        source:(selectedRecord2.length>0?selectedRecord2[0].material_id:0)+'_material'});
                     return x.data;}}
            />
            <ProFormSelect name='material_id2' label='新SKU码' width={300} 
                 showSearch
                 options={moptions}
                 fieldProps={{
                  async onSearch(value) {
                     // alert(value);
                     const x=await s_getSelectData({x_id:1,source:'material_'+value});
                     setMoptions(x.data);
                  },
                 }}
                
            />
            <ProFormSelect name='card_id' label='工序' width={300} 
                request={async ()=>{
                     const x=await s_getSelectData({x_id:1,source:'craft_card'});
                     return x.data;}}
            />
            <ProFormSelect name='classes_id' label='班次' width={300} 
               request={async ()=>{
                  const x=await s_getSelectData({x_id:1,source:'base_classes'});
                  return x.data;}}
            />
            <ProFormDigit name='price' label='单价' width={300} />
                     
            <ProFormTextArea name='memo' label='备注' width={300} />

            <ProFormRadio.Group name='status' label='状态' width={200} 
               rules={[{required:true,message:'必填项'}]}
               options={[{value:1,label:'正常'},{value:2,label:'关闭'},{value:3,label:'删除'}]}
            />
            <Row gutter={8}>
               <Col span={16}>
                   <ProFormDigit name='default_rate' label='默认系数' width={300} />
               </Col>
               <Col span={8}>
                    <Button onClick={()=>setRate()}>设置系数表</Button>
               </Col>
            </Row>
         </ProForm>
         </ProCard>
       </Modal>

       {/* 系统表设置----------- */}
       <Modal  open={openRate} width={1000} okButtonProps={{hidden:true}} cancelButtonProps={{hidden:true}} closable
              onCancel={()=>exitRatio()} onClose={()=>exitRatio()} destroyOnClose>
              <ProCard title='工资系数表' style={{height:800,overflow:'auto'}}
                 extra={<Space>
                     <Button onClick={()=>addRatio()}>新增</Button>
                     {/* <Button onClick={()=>editRatio()}>编辑</Button> */}
                     <Button onClick={()=>saveRatio()}>保存</Button>
                     <Button onClick={()=>exitRatio()}>退出</Button>
                 </Space>}
              >
              <ProForm formRef={formRef_rate} layout="horizontal" labelAlign="left" labelCol={{offset:0,span:5}}
                 submitter={false} initialValues={{status:1,isdefault:0}}
              >
               <ProFormText name='id' hidden/>
               <ProFormText name='mid' hidden />
               <Row gutter={8}>
                  <Col span={10}>
                     <ProFormText name='item_name' label='系数名称'/>
                     <ProFormText name='item_rate' label='系数值'/>
                  </Col>
                  <Col span={6}>
                     <ProFormRadio.Group name='isdefault' label='默认'
                        options={[{value:0,label:'否'},{value:1,label:'是'}]}
                     />
                     <ProFormRadio.Group name='status' label='状态'
                         options={[{value:1,label:'有效'},{value:2,label:'关闭'}]}
                       />
                  </Col>
                  <Col span={8}>
                     <ProFormTextArea name='memo' label='备注'/>

                  </Col>
               </Row>
               </ProForm>
              <ProTable<DataType3>
                 actionRef={actionRef_ratio}
                 search={false}
                 columns={columns3}
                 options={false}
                 request={async ()=>{
                    const x=await s_getcommontableinfo({source:'produce_pricerate_detail_ratio',x_id:1,
                        id:selectedRecord2.length>0?selectedRecord2[0].id:0
                     });
                    return{
                     data:x.data[0],
                     success:true,
                    }
                 }}
                 rowKey='id'
                 rowSelection={{
                  type:'radio',
                  onChange(selectedRowKeys, selectedRows, info) {
                     if(selectedRows.length>0)
                         setEtype3(0);
                        formRef_rate.current?.setFieldsValue(
                         { item_name:selectedRows.length>0?selectedRows[0].item_name:'',
                           item_rate:selectedRows.length>0?selectedRows[0].item_rate:0,
                           isdefault:selectedRows.length>0?selectedRows[0].isdefault:0,
                           status:selectedRows.length>0?selectedRows[0].status:0,
                           id:selectedRows.length>0?selectedRows[0].id:0,
                           mid:selectedRows.length>0?selectedRows[0].mid:0,
                           memo:selectedRows.length>0?selectedRows[0].memo:0,
                         }
                     );
                  },
                 }}
                 />
                 
              </ProCard>  
        </Modal>
    </>;
};

export default App;